/*
 * FileArgumentSource.cpp
 *
 *  Created on: 26 juin 2011
 *      Author: Pierrick Caillon <pierrick@megami.fr>
 */

#include "FileArgumentSource.h"
#include "CommandLine.h"
#include <unistd.h>
#include <fstream>
#include "SourceBuilder.h"

namespace po = boost::program_options;
po::options_description fileOptions("File source");
po::options_description &initFileParams();
CommandLine::Register regIFP(initFileParams, CommandLine::OPT_CLI_HELP);
CommandLine::Register regIFPp("input-file", 1);

SourceBuilder::Registrer regFAS(FileArgumentSource::get_Instance,
		FileArgumentSource::is_Valid);

FileArgumentSource::FileArgumentSource()
{
}

FileArgumentSource::~FileArgumentSource()
{
}

ISource *FileArgumentSource::get_Instance()
{
	return new FileArgumentSource();
}

NamedBinaryTag::DataFile FileArgumentSource::GetDataFile()
{
	std::string value = CommandLine::get_Item("input-file").as<std::string> ();
	std::istream *source = NULL;
	std::ifstream sourceFile;
	if (value == "-")
	{
		source = &std::cin;
	}
	else
	{
		sourceFile.open(value.c_str(),
				std::ios_base::in | std::ios_base::binary);
		if (sourceFile)
			source = &sourceFile;
		else
			std::cerr << __N("Unable to load the source file.\n");
	}
	NamedBinaryTag::DataFile nbtFile;
	if (source != NULL)
	{
		try
		{
			nbtFile.Load(*source);
		} catch (std::exception e)
		{
			std::cerr << __N("Error while reading source: ") << e.what()
					<< std::endl;
		}
	}
	return nbtFile;
}

bool FileArgumentSource::is_Valid()
{
	const po::variable_value &valueVar = CommandLine::get_Item("input-file");
	if (valueVar.empty())
		return false;
	std::string value = valueVar.as<std::string> ();
	return ((value == "-") || (access(value.c_str(), R_OK) == 0));
}

po::options_description &initFileParams()
{
	fileOptions.add_options()("input-file,I", po::value<std::string>(),
			"input Minecraft map item file. Mandatory if no other source.\nMatch the <filename> parameter in example.");
	return fileOptions;
}
